package com.kim.smartring.adapter;

import java.util.ArrayList;
import java.util.Locale;

import android.app.Activity;
import android.bluetooth.BluetoothGattCharacteristic;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.kim.smartring.R;
import com.kim.smartring.ble.BleNamesResolver;

public class CharacteristicsAdapter extends BaseAdapter {
	private ArrayList<BluetoothGattCharacteristic> mCharacteristics;
	private LayoutInflater mInflater;

	public CharacteristicsAdapter(Activity parent) {
		super();
		mCharacteristics = new ArrayList<BluetoothGattCharacteristic>();
		mInflater = parent.getLayoutInflater();
	}

	public void addCharacteristic(BluetoothGattCharacteristic ch) {
		if (mCharacteristics.contains(ch) == false) {
			mCharacteristics.add(ch);
		}
	}

	public BluetoothGattCharacteristic getCharacteristic(int index) {
		return mCharacteristics.get(index);
	}

	public void clearList() {
		mCharacteristics.clear();
	}

	@Override
	public int getCount() {
		return mCharacteristics.size();
	}

	@Override
	public Object getItem(int position) {
		return getCharacteristic(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// get already available view or create new if necessary
		ViewHolder fields;
		if (convertView == null) {
			convertView = mInflater.inflate(
					R.layout.item_peripheral_device_characteristic, null);
			fields = new ViewHolder();
			fields.charName = (TextView) convertView
					.findViewById(R.id.peripheral_list_characteristic_name);
			fields.charUuid = (TextView) convertView
					.findViewById(R.id.peripheral_list_characteristic_uuid);
			convertView.setTag(fields);
		} else {
			fields = (ViewHolder) convertView.getTag();
		}

		// set proper values into the view
		BluetoothGattCharacteristic ch = getCharacteristic(position);
		String uuid = ch.getUuid().toString().toLowerCase(Locale.getDefault());
		String name = BleNamesResolver.resolveCharacteristicName(uuid);

		fields.charName.setText(name);
		fields.charUuid.setText(uuid);

		return convertView;
	}

	private class ViewHolder {
		TextView charName;
		TextView charUuid;
	}
}
